using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DebugCompanion.Engine;

namespace DebugCompanion
{
	static class AssemblyCacheController
	{
		public static List<AssemblyInfo> Init(List<AssemblyInfo> assemblies)
		{
			List<AssemblyInfo> res = null;
			if (assemblies.Count != 0)
			{
				MethodInvoker operation = delegate
				{
					res = DoInit(assemblies);
				};
				MethodInvoker finished = delegate
				{
					Thread.Sleep(2000);
					if (res == null || res.Count == assemblies.Count)
						ProgressDlg.Terminate();
				};
				MethodInvoker terminate = delegate { AssemblyProcessor.TerminateProcessing(); };
				ProgressDlg.Show("Please wait...", "Preparing debug data", operation, finished, terminate);
			}
			return res;
		}

		static List<AssemblyInfo> DoInit(List<AssemblyInfo> assemblies)
		{
			try
			{
				List<AssemblyInfo> processed = new List<AssemblyInfo>();
				string cachePath = EnvironmentUtil.GetCachePath();

				int i = 0;
				foreach (AssemblyInfo asm in assemblies)
				{
					try
					{
						ProgressDlg.AddLogMessage("Processing " + asm.DisplayName + Environment.NewLine);
						if (!IsAlreadyCached(asm))
						{
							AssemblyProcessor.GenerateDebugAssembly(asm, cachePath);
						}
						processed.Add(asm);
					}
					catch (Exception exc)
					{
						if (exc is AssemblyProcessor.AbortException)
							throw;
						Trace.WriteLine(exc);
						ProgressDlg.AddLogMessage("!An error occured: " + asm.DisplayName + " "
							+ exc.Message + Environment.NewLine);
					}
					i++;
					ProgressDlg.SetProgress(0, assemblies.Count, i);
				}

				return processed;
			}
			catch (AssemblyProcessor.AbortException)
			{
			}
			catch
			{
			}
			return null;
		}

		static bool IsAlreadyCached(AssemblyInfo asm)
		{
			string path = EnvironmentUtil.GetAsmCachePath(asm);
			if (!Directory.Exists(path))
				return false;

			if (!File.Exists(path + "\\" + asm.Name))
				return false;

			return true;
		}
	}
}
